import subprocess
import time

import traceback
import subprocess as sp

import tempfile

try:

    try:
        tmp = sp.Popen('adb shell wm size', shell=True, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
        resolution, _ = tmp.communicate()
        wh = resolution.strip().decode().split(': ')[1].split('x')
    except Exception as _:
        print('ABD failed to connect devices, please run "adb devices" to find more error messages!')
    # 2. 获取屏幕流。
    screen_cmd = ['adb', 'exec-out', 'screencap', '-p']

    out_temp = tempfile.SpooledTemporaryFile(max_size=10 * 1000)

    fileno = out_temp.fileno()

    obj = subprocess.Popen(screen_cmd, stdout=fileno, stderr=fileno, shell=True)
    obj.wait()
    out_temp.seek(0)
    lines = out_temp.readlines()
    print("结果：", lines)
    while len(lines) != 0:
        lines = out_temp.readlines()
        print("结果：", lines)

    out_temp.close()

except (Exception):

    print(traceback.format_exc())
